package com.xinwangai.jingbai.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.xinwangai.jingbai.common.Constants;
import com.xinwangai.jingbai.pojo.DTO.CheckinActivityDTO;
import com.xinwangai.jingbai.pojo.VO.CheckinActivity;
import com.xinwangai.jingbai.pojo.VO.CheckinRecord;
import com.xinwangai.jingbai.pojo.VO.CheckinStats;
import com.xinwangai.jingbai.pojo.VO.PageResult;
import com.xinwangai.jingbai.service.CheckinService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 简化版打卡系统控制器
 * 移除子打卡概念，只保留主打卡活动
 *
 * @author guo.wenliang
 * @since 2025/7/16 20:45
 */
@RestController
@RequestMapping("/checkin")
@CrossOrigin(origins = "*")
public class CheckinController {
    private static final Logger logger = LoggerFactory.getLogger(CheckinController.class);

    @Autowired
    private CheckinService checkinService;

    /**
     * 创建打卡活动
     */
    @PostMapping("/createCheckinActivity")
    public String createCheckinActivity(@RequestBody CheckinActivity checkinActivity) {
        JSONObject jsonObject = new JSONObject();
        try {
            int result = checkinService.createCheckinActivity(checkinActivity);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "创建成功");
                jsonObject.put("data", result);
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "创建失败");
            }
        }
        catch (Exception e) {
            logger.error("创建打卡活动失败", e);
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "创建失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 更新打卡活动
     */
    @PostMapping("/updateCheckinActivity")
    public String updateCheckinActivity(@RequestBody CheckinActivity checkinActivity) {
        JSONObject jsonObject = new JSONObject();
        try {
            int result = checkinService.updateCheckinActivity(checkinActivity);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "更新成功");
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "更新失败");
            }
        }
        catch (Exception e) {
            logger.error("更新打卡活动失败", e);
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "更新失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 删除打卡活动
     */
    @PostMapping("/deleteCheckinActivity")
    public String deleteCheckinActivity(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long id = Long.valueOf(params.get("id").toString());
            Long userId = Long.valueOf(params.get("userId").toString());
            int result = checkinService.deleteCheckinActivity(id, userId);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "删除成功");
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "删除失败");
            }
        }
        catch (Exception e) {
            logger.error("删除打卡活动失败", e);
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "删除失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 获取打卡活动详情
     */
    @PostMapping("/getCheckinActivityDetail")
    public String getCheckinActivityDetail(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long id = Long.valueOf(params.get("id").toString());
            CheckinActivity result = checkinService.getCheckinActivityDetail(id);
            if (result != null) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "获取成功");
                jsonObject.put("data", result);
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "活动不存在");
            }
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "获取失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 获取打卡活动列表
     */
    @PostMapping("/getCheckinActivities")
    public String getCheckinActivities(@RequestBody CheckinActivityDTO checkinActivityDTO) {
        JSONObject jsonObject = new JSONObject();
        try {
            PageInfo<CheckinActivity> result = checkinService.getCheckinActivities(checkinActivityDTO);
            jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
            jsonObject.put("msg", "获取成功");
            jsonObject.put("data", result);
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "获取失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 执行打卡
     */
    @PostMapping("/createCheckinRecord")
    public String createCheckinRecord(@RequestBody CheckinRecord checkinRecord) {
        JSONObject jsonObject = new JSONObject();
        try {
            int result = checkinService.createCheckinRecord(checkinRecord);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "打卡成功");
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "打卡失败");
            }
        }
        catch (Exception e) {
            logger.error("创建打卡记录失败", e);
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "打卡失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 更新打卡记录
     */
    @PostMapping("/updateCheckinRecord")
    public String updateCheckinRecord(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long id = Long.valueOf(params.get("id").toString());
            String status = (String) params.get("status");
            String notes = (String) params.get("notes");
            Integer duration = params.get("duration") != null ? Integer.valueOf(params.get("duration").toString()) : null;
            Long userId = Long.valueOf(params.get("userId").toString());

            int result = checkinService.updateCheckinRecord(id, status, notes, duration, userId);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "更新成功");
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "更新失败");
            }
        }
        catch (Exception e) {
            logger.error("更新打卡记录失败", e);
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "更新失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 删除打卡记录
     */
    @PostMapping("/deleteCheckinRecord")
    public String deleteCheckinRecord(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long id = Long.valueOf(params.get("id").toString());
            Long userId = Long.valueOf(params.get("userId").toString());

            int result = checkinService.deleteCheckinRecord(id, userId);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "删除成功");
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "删除失败");
            }
        }
        catch (Exception e) {
            logger.error("删除打卡记录失败", e);
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "删除失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 获取打卡记录列表
     */
    @PostMapping("/getCheckinRecords")
    public String getCheckinRecords(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long activityId = params.get("activityId") != null ? Long.valueOf(params.get("activityId").toString()) : null;
            Long userId = params.get("userId") != null ? Long.valueOf(params.get("userId").toString()) : null;
            String startDate = (String) params.get("startDate");
            String endDate = (String) params.get("endDate");
            Integer pageNum = Integer.valueOf(params.get("pageNum").toString());
            Integer pageSize = Integer.valueOf(params.get("pageSize").toString());

            PageResult<CheckinRecord> result = checkinService.getCheckinRecords(activityId, userId, startDate, endDate, pageNum, pageSize);
            jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
            jsonObject.put("msg", "获取成功");
            jsonObject.put("data", result);
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "获取失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 获取打卡日历数据
     */
    @PostMapping("/getCheckinCalendar")
    public String getCheckinCalendar(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            String year = params.get("year").toString();
            String month = params.get("month").toString();
            Long activityId = params.get("activityId") != null ? Long.valueOf(params.get("activityId").toString()) : null;

            Map<String, Integer> result = checkinService.getCheckinCalendar(userId, year, month, activityId);
            jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
            jsonObject.put("msg", "获取成功");
            jsonObject.put("data", result);
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "获取失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 获取打卡统计数据
     */
    @PostMapping("/getCheckinStats")
    public String getCheckinStats(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            Long activityId = params.get("activityId") != null ? Long.valueOf(params.get("activityId").toString()) : null;
            CheckinStats result = checkinService.getCheckinStats(userId, activityId);
            jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
            jsonObject.put("msg", "获取成功");
            jsonObject.put("data", result);
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "获取失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 获取仪表板统计数据
     */
    @PostMapping("/getDashboardStats")
    public String getDashboardStats(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            Map<String, Object> result = checkinService.getDashboardStats(userId);
            jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
            jsonObject.put("msg", "获取成功");
            jsonObject.put("data", result);
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "获取失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 添加参与人员
     */
    @PostMapping("/addParticipants")
    public String addParticipants(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long activityId = Long.valueOf(params.get("activityId").toString());
            List<String> participants = (List<String>) params.get("participants");

            int result = checkinService.addParticipants(activityId, participants);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "添加成功");
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "添加失败");
            }
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "添加失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 移除参与人员
     */
    @PostMapping("/removeParticipant")
    public String removeParticipant(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long activityId = Long.valueOf(params.get("activityId").toString());
            String participant = (String) params.get("participant");

            int result = checkinService.removeParticipant(activityId, participant);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "移除成功");
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "移除失败");
            }
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "移除失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 获取参与者列表
     */
    @PostMapping("/getParticipants")
    public String getParticipants(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long activityId = Long.valueOf(params.get("activityId").toString());
            List<String> result = checkinService.getParticipants(activityId);
            jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
            jsonObject.put("msg", "获取成功");
            jsonObject.put("data", result);
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "获取失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 加入活动
     */
    @PostMapping("/joinActivity")
    public String joinActivity(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long activityId = Long.valueOf(params.get("activityId").toString());
            Long userId = Long.valueOf(params.get("userId").toString());
            String userName = (String) params.get("userName");

            int result = checkinService.joinActivity(activityId, userId, userName);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "加入成功");
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "加入失败");
            }
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "加入失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 退出活动
     */
    @PostMapping("/leaveActivity")
    public String leaveActivity(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long activityId = Long.valueOf(params.get("activityId").toString());
            Long userId = Long.valueOf(params.get("userId").toString());

            int result = checkinService.leaveActivity(activityId, userId);
            if (result > 0) {
                jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
                jsonObject.put("msg", "退出成功");
            }
            else {
                jsonObject.put("code", Constants.RESP_RESULT_BUSINESS_ERROR);
                jsonObject.put("msg", "退出失败");
            }
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "退出失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }

    /**
     * 导出打卡数据
     */
    @PostMapping("/exportCheckinData")
    public String exportCheckinData(@RequestBody Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject();
        try {
            Long activityId = params.get("activityId") != null ? Long.valueOf(params.get("activityId").toString()) : null;
            Long userId = Long.valueOf(params.get("userId").toString());
            String startDate = (String) params.get("startDate");
            String endDate = (String) params.get("endDate");
            String format = (String) params.get("format");

            // 这里应该返回文件流，暂时返回成功消息
            jsonObject.put("code", Constants.RESP_RESULT_SUCCESS);
            jsonObject.put("msg", "导出功能待实现");
        }
        catch (Exception e) {
            jsonObject.put("code", Constants.RESP_RESULT_SYSTEM_ERROR);
            jsonObject.put("msg", "导出失败：" + e.getMessage());
        }
        return jsonObject.toJSONString();
    }
}
